import React, { Component } from 'react';
import TextField from '@material-ui/core/TextField';
import Grid from '@material-ui/core/Grid';
import AddIcon from '@material-ui/icons/Add';
import Button from '@material-ui/core/Button';
import Dialog from '@material-ui/core/Dialog';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import DialogContentText from '@material-ui/core/DialogContentText';
import DialogTitle from '@material-ui/core/DialogTitle';
import DeleteForeverIcon from '@material-ui/icons/DeleteForever';
import PublishIcon from '@material-ui/icons/Publish';
import $ from 'jquery';
import Container from '@material-ui/core/Container';
/**
 * 成绩系数输入
 */
class WeightInputGroup extends Component {
    constructor(props) {
        super(props);
        this.query = this.props.location.query;//传入的参数
        //测试数据,防止每次刷新都无数据导致报错
        if (!this.query) {
            this.query = {
                "_id": "5f4e1da702e91822e86f38d8",
                "courseid": "5.1",
                "coursenumber": "5",
                "coursekind": "必修课",
                "coursename": "软件设计与体系结构",
                "teachernumber": "5",
                "assessmentmethod": "考试",
                "classlist": [
                    "2017240206",
                    "2017240207"
                ],
                "term": "2020-2021第一学期",
                "status": 0,
                "gradepecents": {
                    '考试成绩': 0.7,
                    '平时成绩': 0.3,
                }
            }
        }
        this.testApi = 'http://4ybhus.natappfree.cc/user/addgradepecents';


        this.state = {
            api:this.props.api||this.testApi,
            courseid :this.query.courseid,
            term:this.query.term,
            gradepecents: this.query.gradepecents || {},//成绩系数
            weightKeys:{},
            addDialog: false,//用于输入成绩系数名称的对话框的开启状态
            alertDialog:false,//警告对话框
            newWeightName:'',//新系数的名字
            removeWeightName:'',//正在删除的系数的名字
        }
        this.nextKey=1;
        //为每个成绩系数分配key值
        for(let weightName in this.state.gradepecents){
            this.state.weightKeys[weightName]=this.getNextKey();//生成key值
        }
        

    }

    getNextKey=()=>{
        return this.nextKey++;
    }



    handleDialogInputChange=(event)=>{
        this.setState({
            newWeightName:event.target.value
        });
    }

    handleInputChange=(event,weightName)=>{
        let curState = this.state;
        curState.gradepecents[weightName]=Number(event.target.value);
        this.setState(curState);
    }



    /**
     * 添加成绩系数
     * @param {成绩系数名} weightName 
     */
    addWeight = (weightName) => {
        if(weightName in this.state.gradepecents) return;//如果已经存在则返回
        
        this.setState((state) => {
            state.gradepecents[weightName]=0;
            state.weightKeys[weightName] = this.getNextKey();//为新生成的成绩系数生成key
            return state;
        })
    }

    removeWeight = (weightName) =>{
        if(!(weightName in this.state.gradepecents)) return;//如果不存在，则返回
        this.setState((state) => {
            delete state.gradepecents[weightName];
            delete state.weightKeys[weightName];
            return state;
        })
    }

    /**
     * 打开对话框
     * @param {} event 
     */
    openDialog = (event,dialogName,weightName) => {
        this.setState({
            [dialogName]:true,
            removeWeightName:weightName,
        })
    }

    /**
     * 关闭对话框
     * @param {} event 
     * @param {附加操作} op 
     */
    closeDialog = (event,dialogName,op) => {
        this.setState({
            [dialogName]:false
        })
        if(op==='add'){
            //添加成绩系数
            this.addWeight(this.state.newWeightName);
        }else if(op==='remove'){
            //删除成绩系数
            this.removeWeight(this.state.removeWeightName);
        }
    }

    

    /**
     * 提交对成绩系数的改变
     */
    submitChange=()=>{
        let data = {
            gradepecents:this.state.gradepecents,
            courseid:this.state.courseid,
            term:this.state.term,
        }
        //判断合法性
        let sum=0;
        for(let key in data.gradepecents){
            sum += data.gradepecents[key];
        }
        if(sum !== 1.0){
            alert('成绩系数总和必须为1');
            return;
        }
        $.ajax({
            type: "POST",
            url: this.state.api,
            contentType: "application/json; charset=utf-8",
            data: JSON.stringify(data),
            dataType: "text",
            success: function (msg) {
                
                if(msg==='ok'){
                    alert("修改成功");
                }else{
                    alert("修改失败");
                }
            },
            error: function (message) {
                alert("数据提交失败");
            }
        });
        
    }


    render() {
        return (
            <Container maxWidth="xs">
            <Grid container>
                {Object.keys(this.state.gradepecents).map(
                    (weightName,index) => {
                        let key = this.state.weightKeys[weightName];
                        return (
                            <Grid item xs={12}>
                                {/**此处如果使用 weightName作为key会出现bug*/}
                                <TextField 
                                    key={key} 
                                    id="standard-basic" 
                                    label={weightName} 
                                    defaultValue={this.state.gradepecents[weightName]} 
                                    type="number"
                                    onChange={(e)=>this.handleInputChange(e,weightName)}
                                    required
                                />
                                {/**记录一下修了一个下午的bug：按钮和文本域的key值冲突导致各种奇怪的现象，找了很久最后才发现是这个错误
                                 * 所以将其改成：文本域分配唯一的正数key，对应的按钮取对应的负数。
                                 */}
                                <Button
                                    key={-key}
                                    variant="contained"
                                    color="secondary"
                                    endIcon={<DeleteForeverIcon/>}
                                    onClick={(e)=>this.openDialog(e,'alertDialog',weightName)}
                                >
                                    删除
                                </Button>
                            </Grid>
                        );
                    }


                )}
                <Grid item xs={12}>
                    <Button
                        variant="contained"
                        color="primary"
                        endIcon={<AddIcon/>}
                        onClick={(e)=>this.openDialog(e,'addDialog')}
                    >
                        添加
                    </Button>
                    
                </Grid>
                <Grid item xs={12}>
                    <Button
                        variant="contained"
                        color="primary"
                        endIcon={<PublishIcon/>}
                        onClick={(e)=>this.submitChange(e)}
                    >
                        提交
                    </Button>
                </Grid>
                {/**对话框 */}
                <Dialog 
                    name='addDialog' 
                    open={this.state.addDialog} 
                    onClose={(e)=>this.closeDialog(e,'addDialog')} 
                    aria-labelledby="form-dialog-title">
                    <DialogTitle id="form-dialog-title">新增成绩系数</DialogTitle>
                    <DialogContent>
                        <DialogContentText>
                            请填写新增的成绩系数的名称。<br/>
                            未提交修改之前，不会真正修改，退出此页即可撤销。
                        </DialogContentText>
                        <TextField
                            autoFocus
                            margin="dense"
                            id="name"
                            label="成绩系数名"
                            type="text"
                            fullWidth
                            onChange={this.handleDialogInputChange}
                        />
                    </DialogContent>
                    <DialogActions>
                        <Button onClick={(e)=>this.closeDialog(e,'addDialog')} color="primary">
                            取消
                        </Button>
                        <Button onClick={(e)=>this.closeDialog(e,'addDialog','add')} color="primary">
                            添加
                        </Button>
                    </DialogActions>
                </Dialog>
                {/**警告对话框 */}
                <Dialog
                    name='alertDialog'
                    open={this.state.alertDialog}
                    onClose={(e)=>this.closeDialog(e,'alertDialog')}
                    aria-labelledby="alert-dialog-title"
                    aria-describedby="alert-dialog-description"
                >
                    <DialogTitle id="alert-dialog-title">删除成绩系数</DialogTitle>
                    <DialogContent>
                    <DialogContentText id="alert-dialog-description">
                        你确定要删除成绩系数：【{this.state.removeWeightName}】吗？<br/>
                        未提交修改之前，不会真正修改，退出此页即可撤销。
                    </DialogContentText>
                    </DialogContent>
                    <DialogActions>
                    <Button onClick={(e)=>this.closeDialog(e,'alertDialog')} color="primary">
                        取消
                    </Button>
                    <Button onClick={(e)=>this.closeDialog(e,'alertDialog','remove')} color="primary" autoFocus>
                        删除
                    </Button>
                    </DialogActions>
                </Dialog>
            </Grid>
            </Container>
        );
    }
}

export default WeightInputGroup;